package com.wy.shopping.controller;

import java.util.*;
import java.util.concurrent.TimeUnit;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wy.shopping.entity.GoodsEntity;
import com.wy.shopping.entity.MiaoshaActivityEntity;
import com.wy.shopping.entity.MiaoshaOrderEntity;
import com.wy.shopping.service.GoodsService;
import com.wy.shopping.service.MiaoshaActivityService;
import com.wy.shopping.service.MiaoshaOrderService;
import com.wy.shopping.util.AliPayUtil;
import com.wy.shopping.util.IdWorker;
import com.wy.shopping.vo.AlipayBean;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.wy.shopping.entity.OrderInfoEntity;
import com.wy.shopping.service.OrderInfoService;
import com.wy.common.utils.PageUtils;
import com.wy.common.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 *
 * @author wangyu
 * @email sunlightcs@gmail.com
 * @date 2022-02-22 18:48:20
 */
@Controller
@RequestMapping("shopping/orderinfo")
public class OrderInfoController {
    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private MiaoshaOrderService miaoshaOrderService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private MiaoshaActivityService miaoshaActivityService;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = orderInfoService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @ResponseBody
    public R info(@PathVariable("id") Long id) {
		OrderInfoEntity orderInfo = orderInfoService.getById(id);

        return R.ok().put("orderInfo", orderInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @ResponseBody
    public R save(@RequestBody OrderInfoEntity orderInfo) {

        RLock orderLock = redissonClient.getLock("orderLock");
        try {
            //获取锁
            boolean b = orderLock.tryLock(30, 10, TimeUnit.SECONDS);
            if (b) {
                MiaoshaActivityEntity miaoshaId = miaoshaActivityService.getById(orderInfo.getId());
                if (miaoshaId.getStockCount() == null || miaoshaId.getStockCount() == 0) {
                    return R.error("库存数量不足");
                }
                QueryWrapper<OrderInfoEntity> wrapper = new QueryWrapper<OrderInfoEntity>().eq("user_id", orderInfo.getUserId())
                        .eq("goods_id",orderInfo.getGoodsId());

                OrderInfoEntity one = orderInfoService.getOne(wrapper);
                MiaoshaOrderEntity miaoshaOrderEntity = new MiaoshaOrderEntity();
                if (one == null) {
                    orderInfo.setId(idWorker.nextId());
                    orderInfo.setCreateDate(new Date());
                    orderInfoService.save(orderInfo);

                    miaoshaOrderEntity.setUserId(orderInfo.getUserId());
                    miaoshaOrderEntity.setOrderId(orderInfo.getId());
                    miaoshaOrderEntity.setGoodsId(orderInfo.getGoodsId());
                    miaoshaOrderService.save(miaoshaOrderEntity);
                    //支付成功商品库存减一
                    GoodsEntity goodsEntity = goodsService.getById(orderInfo.getGoodsId());
                    //判断商品库存为-1时不对库存进行减一
                    if (goodsEntity.getGoodsStock() != -1) {
                        goodsEntity.setGoodsStock(goodsEntity.getGoodsStock()-1);
                        goodsService.updateById(goodsEntity);
                    }
                    //支付成功秒杀活动库存减一
                    QueryWrapper<MiaoshaActivityEntity> wrapper1 = new QueryWrapper<>();
                    wrapper1.eq("goods_id",orderInfo.getGoodsId());
                    MiaoshaActivityEntity activityEntity = miaoshaActivityService.getOne(wrapper1);
                    activityEntity.setStockCount(activityEntity.getStockCount()-1);
                    miaoshaActivityService.updateById(activityEntity);
                    return R.ok();
                }
                return R.error("不可秒杀多件同样的商品");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放锁
            orderLock.unlock();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @ResponseBody
    public R update(@RequestBody OrderInfoEntity orderInfo){
        orderInfo.setStatus(4);
        boolean b = orderInfoService.updateById(orderInfo);
        if (b) {
            //取消成功商品库存加一
            GoodsEntity goodsEntity = goodsService.getById(orderInfo.getGoodsId());
            //判断商品库存为-1时不对库存进行减一
            if (goodsEntity.getGoodsStock() != -1) {
                goodsEntity.setGoodsStock(goodsEntity.getGoodsStock()+1);
                goodsService.updateById(goodsEntity);
            }
            //取消成功秒杀活动库存加一
            QueryWrapper<MiaoshaActivityEntity> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("goods_id",orderInfo.getGoodsId());
            MiaoshaActivityEntity activityEntity = miaoshaActivityService.getOne(wrapper1);
            activityEntity.setStockCount(activityEntity.getStockCount()+1);
            miaoshaActivityService.updateById(activityEntity);
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public R delete(@RequestBody Long[] ids){
		orderInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 订单支付
     */
    @RequestMapping("/payorder")
    @ResponseBody
    public R payorder(@RequestBody OrderInfoEntity orderInfo) throws AlipayApiException {
        OrderInfoEntity byId = orderInfoService.getById(orderInfo.getId());
        AlipayBean alipayBean = new AlipayBean();
        alipayBean.setOut_trade_no(String.valueOf(byId.getId()));
        alipayBean.setSubject(byId.getGoodsName());
        alipayBean.setTotal_amount(new StringBuffer().append(byId.getGoodsPrice()));
        alipayBean.setBody(byId.getGoodsName());
        String connect = AliPayUtil.connect(alipayBean);
        return R.ok().put("connect",connect);
    }

    /**
     * 支付回调接口
     */
    @RequestMapping("/callBack")
    public String callBack(HttpServletRequest request) throws Exception {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        String orderId = requestParams.get("out_trade_no")[0];
        System.out.println(orderId);
        OrderInfoEntity byId = orderInfoService.getById(orderId);
        byId.setStatus(1);
        byId.setPayDate(new Date());
        orderInfoService.updateById(byId);

        return "redirect:http://127.0.0.1:5500/orderList.html";
    }
}
